package com.hzgj.bcl.soa.command;

import com.google.common.collect.Maps;
import com.hzgj.bcl.soa.collector.JmxCollector;
import com.hzgj.bcl.soa.registry.RegistryUpdater;
import com.hzgj.bcl.util.lang.StrKit;

import java.util.Map;

import static com.hzgj.bcl.soa.command.CommandsInitializer.UPORDOWNSERVICE_COMMAND;
import static com.hzgj.bcl.soa.util.Constants.OBJECTNAME_PREFIX;

/**
 * Created by Administrator on 2016/9/18.
 */
public class UpOrDownServiceCommand extends JmxInvokeCommand {

    @Override
    public String getName() {
        return UPORDOWNSERVICE_COMMAND;
    }

    @Override
    Map<String, Object> jmxInvoke(JmxCollector jmxCollector, CommandOptions commandOptions, String host, String port) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            String service = commandOptions.params.get("service")[0];
            String _down = commandOptions.params.get("down")[0];
            boolean down = StrKit.isBlank(_down) ? false : _down.equals("1") ? true : false;
            RegistryUpdater.Result ret = jmxInvoke(jmxCollector, service, host + ":" + port, down);
            if (!ret.isSuccess()) {
                result.put("message", ret.getInfo());
                result.put("status", "failure");
            } else {
                result.put("status", "success");
            }
        } catch (Exception e) {
            logger.error("{}", e);
            result.put("message", e.getMessage());
            result.put("status", "failure");
        }
        return result;
    }

    public RegistryUpdater.Result jmxInvoke(JmxCollector jmxCollector, String service, String address, boolean down) throws Exception {
        return (RegistryUpdater.Result) jmxCollector.invoke(OBJECTNAME_PREFIX + "registry,name=RegistryService", "upOrDownService",
                new Object[]{service, address, down}, new String[]{String.class.getName(), String.class.getName(), boolean.class.getName()});
    }
}
